<template>
  <div class="app-container">
    <div class="custom_card_0" v-show="showSearch">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="客户名称" prop="memberName">
          <el-input
            v-model="queryParams.memberName"
            placeholder="请输入客户名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="微信昵称" prop="vxName">
          <el-input
            v-model="queryParams.vxName"
            placeholder="请输入微信昵称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="联系方式" prop="memberPhone">
          <el-input
            v-model="queryParams.memberPhone"
            placeholder="请输入联系方式"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="分销状态" prop="qualification">
          <el-select
            v-model="queryParams.qualification"
            placeholder="全部"
            clearable
            size="small"
          >
            <el-option label="启用" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间" prop="registerTime">
          <el-date-picker
            clearable
            size="small"
            v-model="queryParams.registerTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择注册时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="custom_card">
      <el-row :gutter="10" class="mb10">
        <el-col :span="1.5">
          <el-button
            class="sec-plain-btn" size="medium"
            icon="el-icon-download"
            :loading="exportLoading"
            @click="handleExport"
            v-hasPermi="['customer:basic:export']"
            >导出</el-button
          >
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="basicList" border>
        <el-table-column
          label="用户名称"
          align="center"
          prop="memberName"
          min-width="160"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="联系方式"
          align="center"
          prop="memberPhone"
          min-width="160"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="一级分佣金额(元)"
          min-width="180"
          align="center"
          prop="primaryCommissionAmount"
          show-overflow-tooltip
        />
        <el-table-column
          label="一级分佣金百分比(%)"
          min-width="180"
          align="center"
          prop="primaryCommissionPercentage"
          show-overflow-tooltip
        />
        <el-table-column
          label="二级分佣金额(元)"
          min-width="180"
          align="center"
          prop="secondaryCommissionAmount"
          show-overflow-tooltip
        />
        <el-table-column
          label="二级分佣金百分比(%)"
          min-width="180"
          align="center"
          prop="secondaryCommissionPercentage"
          show-overflow-tooltip
        />
        <el-table-column
          label="下级会员数"
          align="center"
          prop="subordinateCount"
          min-width="120"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <div
              @click="handleSubordinate(scope.row, 1)"
              style="color: #0072c6; cursor: pointer"
            >
              {{ scope.row.subordinateCount }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="下级伙伴数"
          align="center"
          prop="partnerCount"
          min-width="120"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <div
              @click="handleSubordinate(scope.row, 0)"
              style="color: #0072c6; cursor: pointer"
            >
              {{ scope.row.partnerCount }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="分销状态"
          align="center"
          prop="qualification"
          min-width="120"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{scope.row.qualification==1?'停用':'启用'}}
          </template>
        </el-table-column>
        <el-table-column
          label="注册时间"
          align="center"
          prop="registerTime"
          min-width="160"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.registerTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="邀请人" align="center" prop="inviterName" />
        <el-table-column
          label="邀请人联系方式"
          align="center"
          prop="inviterPhone"
          min-width="160"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="所属租户"
          align="center"
          prop="tenantName"
          min-width="120"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="操作"
          align="center"
          fixed="left"
          width="120"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleDetail(scope.row)"
              v-hasPermi="['customer:basic:query']"
              >详情</el-button
            >
            <!-- 停用分销资格-->
            <el-dropdown
              v-if="scope.row.qualification === 0"
              size="mini"
              @command="(command) => handleCommand(command, scope.row)"
            >
              <span class="el-dropdown-link">
                <i class="el-icon-d-arrow-right el-icon--right"></i>更多
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="stopQualification"
                  >停用分销资格</el-dropdown-item
                >
                <el-dropdown-item command="updateData" icon="el-icon-key"
                  >修改</el-dropdown-item
                >
                <el-dropdown-item command="suborsdinate" icon="el-icon-key"
                  >查看下级</el-dropdown-item
                >
                <el-dropdown-item
                  v-if="
                    scope.row.inviterName === '' ||
                    scope.row.inviterName === null
                  "
                  command="setSuperior"
                  icon="el-icon-key"
                  >设置上级</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
            <!-- 停用分销资格-->
            <el-dropdown
              v-if="scope.row.qualification === 1"
              size="mini"
              @command="(command) => handleCommand(command, scope.row)"
            >
              <span class="el-dropdown-link">
                <i class="el-icon-d-arrow-right el-icon--right"></i>更多
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  command="startQualification"
                  icon="el-icon-key"
                  >启用分销资格</el-dropdown-item
                >
                <el-dropdown-item
                  command="updateData"
                  icon="el-icon-key"
                  v-hasPermi="['customer:basic:edit']"
                  >修改</el-dropdown-item
                >
                <el-dropdown-item command="suborsdinate" icon="el-icon-key"
                  >查看下级</el-dropdown-item
                >
                <el-dropdown-item
                  v-if="
                    scope.row.inviterName === '' ||
                    scope.row.inviterName === null
                  "
                  command="setSuperior"
                  icon="el-icon-key"
                  >设置上级</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 编辑 -->
    <el-dialog :title="title" :visible.sync="open"  append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="form.vxUrl">
            <el-form-item label="微信图像" prop="vxUrl">
              <img :src="form.vxUrl" width="40" height="40" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信名称" prop="vxName">
              <el-input v-model="form.vxName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="memberName">
              <el-input v-model="form.memberName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="memberPhone">
              <el-input v-model="form.memberPhone" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="一级佣金" prop="primaryAmountChecked">
              <el-row>
                <el-col :span="12">
                  <el-select
                    v-model="form.primaryAmountChecked"
                    @change="primaryAmount"
                    style="width: calc(100% - 6px)"
                  >
                    <el-option label="按固定金额" :value="1"></el-option>
                    <el-option label="按百分比" :value="2"></el-option>
                  </el-select>
                </el-col>
                <el-col :span="12">
                  <!-- 按固定金额 -->
                  <template v-if="form.primaryAmountChecked == 1">
                    <el-input
                      v-model="form.primaryCommissionAmount"
                      style="width: calc(100% - 6px); margin-left: 6px"
                      placeholder="一级分销佣金金额（最多两位小数）"
                    >
                      <div slot="suffix" style="margin-right: 8px">元</div>
                    </el-input>
                  </template>
                  <!-- 按百分比 -->
                  <template v-if="form.primaryAmountChecked == 2">
                    <el-input
                      v-model="form.primaryCommissionPercentage"
                      style="width: calc(100% - 6px); margin-left: 6px"
                      placeholder="一级分销佣金百分比（最多两位小数）"
                    >
                      <div slot="suffix" style="margin-right: 8px">%</div>
                    </el-input>
                  </template>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="二级佣金" prop="secondaryAmountChecked">
              <el-row>
                <el-col :span="12">
                  <el-select
                    v-model="form.secondaryAmountChecked"
                    @change="secondaryAmount"
                    style="width: calc(100% - 6px)"
                  >
                    <el-option label="按固定金额" :value="1"></el-option>
                    <el-option label="按百分比" :value="2"></el-option>
                  </el-select>
                </el-col>
                <el-col :span="12">
                  <!-- 按固定金额 -->
                  <template v-if="form.secondaryAmountChecked == 1">
                    <el-input
                      v-model="form.secondaryCommissionAmount"
                      placeholder="二级分销佣金金额（最多两位小数）"
                      style="width: calc(100% - 6px); margin-left: 6px"
                    >
                      <div slot="suffix" style="margin-right: 8px">元</div>
                    </el-input>
                  </template>
                  <!-- 按百分比 -->
                  <template v-if="form.secondaryAmountChecked == 2">
                    <el-input
                      v-model="form.secondaryCommissionPercentage"
                      style="width: calc(100% - 6px); margin-left: 6px"
                      placeholder="二级分销佣金百分比（最多两位小数）"
                    >
                      <div slot="suffix" style="margin-right: 8px">%</div>
                    </el-input>
                  </template>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 设置上级-->
    <el-dialog
      :title="title"
      :visible.sync="superior"
      width="950px"
      append-to-body
    >
      <el-form
        :model="superiorParams"
        ref="superiorParams"
        :inline="true"
        label-width="70px"
        class="search"
      >
        <el-form-item label="客户名称" prop="memberName">
          <el-input
            v-model="superiorParams.memberName"
            placeholder="请输入客户名称"
            clearable
            size="small"
            @keyup.enter.native="superiorHandleQuery"
          />
        </el-form-item>
        <el-form-item label="微信昵称" prop="vxName">
          <el-input
            v-model="superiorParams.vxName"
            placeholder="请输入微信昵称"
            clearable
            size="small"
            @keyup.enter.native="superiorHandleQuery"
          />
        </el-form-item>
        <el-form-item label="联系方式" prop="memberPhone">
          <el-input
            v-model="superiorParams.memberPhone"
            placeholder="请输入联系方式"
            clearable
            size="small"
            @keyup.enter.native="superiorHandleQuery"
          />
        </el-form-item>
        <el-form-item label="注册时间" prop="registerTime">
          <el-date-picker
            clearable
            size="small"
            v-model="superiorParams.registerTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择注册时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="superiorHandleQuery"
            >搜索</el-button
          >
          <el-button
            icon="el-icon-refresh"
            size="mini"
            @click="superiorResetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="superiorList" height="300px" border>
        <el-table-column
          label="成员"
          align="center"
          min-width="120"
          show-overflow-tooltip
          prop="memberName"
        >
          <template slot-scope="scope">
            <span v-html="memberChannel(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column
          label="上级邀请人"
          align="center"
          min-width="120"
          show-overflow-tooltip
          prop="superMemberName"
        >
          <template slot-scope="scope">
            <span v-html="superMemberChannel(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column
          label="注册时间"
          prop="registerTime"
          align="center"
          min-width="160"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.registerTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          fixed="left"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="singleSuperiorInviter(scope.row)"
              v-hasPermi="['customer:basic:query']"
              >设为上级</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        :total="totalSuperior"
        :page.sync="superiorParams.pageNum"
        :limit.sync="superiorParams.pageSize"
        @pagination="superiorLiData"
        :pager-count="5"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  listBasic,
  getBasic,
  addBasic,
  updateBasic,
  exportBasic,
  listMember,
  listPartner,
  startORdisableQualification,
  listSuperior,
  setSuperMember,
} from '@/api/marketing/customer'

export default {
  name: 'Basic',
  dicts: ['sys_available'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      totalDetailed: 0,
      totalWithdrawal: 0,
      totalPartner: 0,
      totalMember: 0,
      totalSuperior: 0,
      //默认标签
      activeName: 'first',
      // 业务客户表格数据
      basicList: [],
      //收益明细
      returnsDetailedList: [],
      //提现明细
      withdrawalRecordList: [],
      //会员明细
      handleMemberList: [],
      //伙伴明细
      handlePartnerList: [],
      //设置上级
      superiorList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      detail: false,
      subordinate: false,
      superior: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        vxName: null,
        memberName: null,
        memberPhone: null,
        registerTime: null,
        qualification: null,
      },
      //设置上级
      superiorParams: {
        pageNum: 1,
        pageSize: 10,
        vxName: null,
        memberName: null,
        memberPhone: null,
        registerTime: null,
        memberNo: null,
      },
      //收益
      detaileParams: {
        pageNum: 1,
        pageSize: 10,
        memberNo: null,
      },
      //提现
      withdrawalParams: {
        pageNum: 1,
        pageSize: 10,
        memberNo: null,
      },
      //会员
      memberParams: {
        pageNum: 1,
        pageSize: 10,
        memberNo: null,
      },
      //伙伴
      partnerParams: {
        pageNum: 1,
        pageSize: 10,
        memberNo: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      subordinateTable: 'first',
    }
  },
  created() {
    this.getList()
  },
  methods: {
    primaryAmount() {
      this.form.primaryCommissionAmount = 0
      this.form.primaryCommissionPercentage = 0
    },
    secondaryAmount() {
      this.form.secondaryCommissionAmount = 0
      this.form.secondaryCommissionPercentage = 0
    },
    handleClick(tab, event) {
      console.log(tab, event)
    },
    handleSubordinateTableClick(tab, event) {
      console.log(tab, event)
    },
    /** 查询业务客户列表 */
    getList() {
      this.loading = true
      listBasic(this.queryParams).then((response) => {
        this.basicList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    cancelDetail() {
      this.detail = false
    },
    cancelSubordinate() {
      this.subordinate = false
    },
    // 表单重置
    reset() {
      this.form = {
        vxName: null,
        memberName: null,
        memberPhone: null,
        registerTime: null,
        primaryAmountChecked: 1, // 一级分销佣金:1按固定金额、2按百分比
        primaryCommissionAmount: 0, // 一级分销佣金金额
        primaryCommissionPercentage: 0, // 一级分销佣金百分比
        secondaryAmountChecked: 1, // 二级分销佣金:1按固定金额、2按百分比
        secondaryCommissionAmount: 0, // 二级分销佣金金额
        secondaryCommissionPercentage: 0, // 	二级分销佣金百分比
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 设置上级搜索按钮操作 */
    superiorHandleQuery() {
      this.superiorParams.pageNum = 1
      this.superiorLiData()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 设置上级重置按钮操作 */
    superiorResetQuery() {
      this.resetForm('superiorParams')
      this.superiorHandleQuery()
    },
    /* 上级列表*/
    superiorLiData() {
      this.loading = true
      listSuperior(this.superiorParams).then((response) => {
        this.superiorList = response.rows
        this.totalSuperior = response.total
        this.loading = false
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加业务客户'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.memberNo
      getBasic(id).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改业务客户'
      })
    },
    //设为上级
    singleSuperiorInviter(row) {
      this.handleConfirm({ msg: '确认要将此分销伙伴设为邀请人吗？' }, (e) => {
        setSuperMember({
          memberNo: this.superiorParams.memberNo,
          superMemberNo: row.memberNo,
          superMemberName: row.memberName,
        }).then((res) => {
          this.$message.success(res.msg)
          this.superior = false
          this.getList()
        })
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.memberNo != null) {
            updateBasic(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addBasic(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const id = row.memberNo
      this.$router.push({
        name: 'customerBasicDetail',
        query: { id: id },
      })
    },
    /** 各种状态弹窗操作 */
    handleConfirm(data, callback) {
      this.$modal.confirm(data.msg).then((e) => {
        callback()
      })
    },
    //更多
    handleCommand(val, row) {
      switch (val) {
        case 'suborsdinate': //查看下级
          this.handleSubordinate(row, 1)
          break
        case 'stopQualification': //停止分销资格
          debugger
          this.handleConfirm({ msg: '确定要停止分销资格？' }, (e) => {
            startORdisableQualification({
              memberNo: row.memberNo,
              qualification: 1,
            }).then((res) => {
              this.$message.success(res.msg)
              this.getList()
            })
          })
          break
        case 'startQualification': //启动分销资格
          debugger
          this.handleConfirm({ msg: '确定要启动分销资格？' }, (e) => {
            startORdisableQualification({
              memberNo: row.memberNo,
              qualification: 0,
            }).then((res) => {
              this.$message.success(res.msg)
              this.getList()
            })
          })
          break
        case 'setSuperior': //设置上级
          this.title = '设置上级'
          //设置上级
          ;(this.superiorParams = {
            pageNum: 1,
            pageSize: 10,
            vxName: null,
            memberName: null,
            memberPhone: null,
            registerTime: null,
            memberNo: null,
          }),
            (this.superior = true)
          this.superiorParams.memberNo = row.memberNo
          this.superiorLiData()
          break
        case 'updateData': //编辑
          this.handleUpdate(row)
          break
      }
    },
    /** 查看下级按钮操作 */
    handleSubordinate(row) {
      const id = row.memberNo
      this.$router.push({
        name: 'customerBasicDownDetail',
        query: {
          id: id,
          directSubordinates: row.directSubordinates,
          indirectSubordinates: row.indirectSubordinates,
        },
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$modal
        .confirm('是否确认导出所有业务客户数据项？')
        .then(() => {
          this.exportLoading = true
          return exportBasic(queryParams)
        })
        .then((response) => {
          this.$download.name(response.msg)
          this.exportLoading = false
        })
        .catch(() => {})
    },
    memberChannel(row) {
      return (
        '昵称：' +
        row.vxName +
        '、' +
        'ID：' +
        row.memberNo +
        '、' +
        '姓名：' +
        row.memberName +
        '、' +
        '手机号：' +
        row.memberPhone
      )
    },
    superMemberChannel(row) {
      if (row.superMemberNo != null && row.superMemberNo != '') {
        return (
          '昵称：' +
          row.superVxName +
          '、' +
          'ID：' +
          row.superMemberNo +
          '、' +
          '姓名：' +
          row.superMemberName +
          '、' +
          '手机号：' +
          row.superMemberPhone
        )
      } else {
        return ''
      }
    },
    inviterLevelChannel(row, column) {
      switch (row.inviterLevel) {
        case 1:
          return '直接下级'
          break
        case 2:
          return '间接下级'
          break
        default:
          return '--'
          break
      }
    },
    tradingChannel(row, column) {
      switch (row.tradingChannel) {
        case 1:
          return '微信'
          break
        case 2:
          return '支付宝'
          break
        case 3:
          return '线下转账'
          break
        case 4:
          return '人工付款'
          break
        default:
          return '--'
          break
      }
    },
    wthdrawalState(row, column) {
      switch (row.wthdrawalState) {
        case 1:
          return '申请中'
          break
        case 2:
          return '待打款'
          break
        case 3:
          return '打款中'
          break
        case 4:
          return '已提现'
          break
        case 5:
          return '提现失败'
          break
        case 6:
          return '提现驳回'
          break
        default:
          return '--'
          break
      }
    },
  },
}
</script>
